package greet

import (
	"github.com/gin-gonic/gin"

	"github.com/zeromicro/go-zero/tools/goctl/api/gogen/workspace/internal/config"
	"github.com/zeromicro/go-zero/tools/goctl/api/gogen/workspace/internal/logic"
	"github.com/zeromicro/go-zero/tools/goctl/api/gogen/workspace/internal/svc"
)

type Handler interface {
	InitRegister(*gin.Engine)
}

func initHandler(cfg config.Config) []Handler {
	svc := svc.NewServiceContext(cfg)

	// new logics
	var (
		adminLogic = logic.NewAdmin(svc)
		userLogic  = logic.NewUser(svc)
	)

	// new handlers
	var (
		aapi = NewAapi(svc, adminLogic, userLogic)
		user = NewUser(svc, userLogic)
	)

	return []Handler{
		aapi,
		user,
	}
}

type handle struct {
	srv  *gin.Engine
	addr string
}

func NewHandle(cfg config.Config) *handle {
	h := &handle{
		srv:  gin.Default(),
		addr: "0.0.0.0:8080",
	}
	if len(cfg.Addr) > 0 {
		h.addr = cfg.Addr
	}

	handlers := initHandler(cfg)
	for _, handler := range handlers {
		handler.InitRegister(h.srv)
	}

	return h
}

func (h *handle) Run() error {
	return h.srv.Run(h.addr)
}
